import Taro from "@tarojs/taro";
class TzVue {
  static EVENT_TYPE = {
    REACH_BOTTOM: "onReachBottom", //滑动到底部
    PULL_DOWN_REFRESH: "onPullDownRefresh", //滑动到底部
  };
  constructor(option) {
    this.init(option);
  }
  init(option) {
    // eslint-disable-next-line no-unused-vars
    for (const key in option) {
      if (Object.hasOwnProperty.call(option, key)) {
        this[key] = option[key];
      }
    }
  }

  //下拉刷新
  onPullDownRefresh = () => {
    const instance = Taro.getCurrentInstance().page;
    const path = (instance.route || instance.path).split("?")[0];
    Taro.eventCenter.trigger(path + TzVue.EVENT_TYPE.PULL_DOWN_REFRESH);
  };
  //滑动底部加载更多
  onReachBottom = function () {
    const path = this.tid.split("?")[0];
    Taro.eventCenter.trigger(path + TzVue.EVENT_TYPE.REACH_BOTTOM);
  };

  //销毁
  unmounted = function () {
    // let instance = Taro.getCurrentInstance().page;
    /**
     * NOTE: unmounted 的时候 Taro.getCurrentInstance().page 拿到的是新打开页面的实例
     * 会导致 off 的事件名对不上，无法正确解除监听
     */
    // const path = (instance.route || instance.path).split("?")[0];
    const path = this.tid?.split("?")[0];
    Taro.eventCenter.off(path + TzVue.EVENT_TYPE.REACH_BOTTOM);
    Taro.eventCenter.off(path + TzVue.EVENT_TYPE.PULL_DOWN_REFRESH);
    // instance = null;
  };
}

/**
 * 下拉刷新回调对外使用
 * @param {function} fn
 */
export const usePullDownRefresh = (fn) => {
  const instance = Taro.getCurrentInstance().page;
  const path = (instance.route || instance.path).split("?")[0];
  Taro.eventCenter.on(path + TzVue.EVENT_TYPE.PULL_DOWN_REFRESH, fn);
};

/**
 * 回调对外使用
 * @param {function} fn
 */
export const useReachBottom = (fn) => {
  const instance = Taro.getCurrentInstance().page;
  const path = (instance.route || instance.path).split("?")[0];
  Taro.eventCenter.on(path + TzVue.EVENT_TYPE.REACH_BOTTOM, fn);
};

export default TzVue;
